/* Filename: shm.c
 * Description: 父子进程用mmap实现共享内存
 * Last modified: humble 20200502 16:01
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MEMSIZE (1024)

static void usage(void);

int main(int argc, char **argv)
{
    char *ptr;
    pid_t pid;

    if(argc != 1){
        fprintf(stderr, "argc !=1");
        usage();
        exit(1);
    }

    ptr = mmap(NULL, MEMSIZE, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
    if(ptr == MAP_FAILED){
        perror("mmap()");
        exit(1);
    }

    pid = fork();
    if(pid < 0){
        perror("fork()");
        munmap(ptr, MEMSIZE);
        exit(1);
    }

    if(pid == 0){ //child write
        strcpy(ptr, "hello");
        munmap(ptr, MEMSIZE);
        exit(0);
    }
    else{ //parent read
        wait(NULL);
        puts(ptr);
        munmap(ptr, MEMSIZE);
        exit(0);
    }

    return 0;
}

static void usage(void)
{
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
